package com.steveproject.parttimeworktree.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.steveproject.parttimeworktree.App;
import com.steveproject.parttimeworktree.R;
import com.steveproject.parttimeworktree.base.BaseActivity;
import com.steveproject.parttimeworktree.base.Constant;
import com.steveproject.parttimeworktree.entity.PartBaseEntity;
import com.steveproject.parttimeworktree.net.MyCallback;
import com.steveproject.parttimeworktree.net.Task;
import com.steveproject.parttimeworktree.utils.BitmapCompressUtils;
import com.steveproject.parttimeworktree.utils.FileUtils;
import com.steveproject.parttimeworktree.utils.ImRezUtils;
import com.steveproject.parttimeworktree.utils.NewsToastUtils;
import com.steveproject.parttimeworktree.utils.PermissionUtils;
import com.steveproject.parttimeworktree.utils.SPUtils;
import com.steveproject.parttimeworktree.utils.ScreenUtil;
import com.steveproject.parttimeworktree.utils.TitleBuilder;
import com.steveproject.parttimeworktree.widget.CenterDialog;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

import static com.steveproject.parttimeworktree.base.Constant.CHANGMYNAME;
import static com.steveproject.parttimeworktree.base.Constant.PICK_PHOTO_CODE;
import static com.steveproject.parttimeworktree.base.Constant.TAKE_PHOTO_CODE;

public class PartMineInfoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储权限
            Manifest.permission.READ_EXTERNAL_STORAGE};

    @BindView(R.id.civ_head)
    CircleImageView circleImageView;
    @BindView(R.id.tv_name)
    TextView tv_name;

    private String serverUrl = "";
    private String nickname = "";

    /**
     * 获取相关权限
     */
    private void getPermission() {
        if (EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            //已经打开权限
            showSelectDialog();
        } else {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、相机使用权限，否则将无法进行修改图像！", 1, PERMISSIONS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (perms.size() == 3) {
            showSelectDialog();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        NewsToastUtils.showToast(App.getContext(), "权限已被拒绝，请手动在设置里面打开权限！");
    }

    /**
     * 选择照片弹窗
     */
    private void showSelectDialog() {
        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(this.getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                //照相
                v.findViewById(R.id.tv_takephoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (PermissionUtils.getInstance().checkPermission(PartMineInfoActivity.this,
                                Manifest.permission.CAMERA)) {
                            File file = new File(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri uri;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                uri = FileProvider.getUriForFile(PartMineInfoActivity.this,
                                        getPackageName() + ".provider", file);
                            } else {
                                uri = Uri.fromFile(file);

                            }
                            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(it, PICK_PHOTO_CODE);
                        } else {
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(PartMineInfoActivity.this);
                        }
                        bottomDialog.dismiss();
                    }
                });
                //选择照片
                v.findViewById(R.id.tv_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(Intent.ACTION_PICK, null);
                        it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(it, TAKE_PHOTO_CODE);
                        bottomDialog.dismiss();
                    }
                });

                //取消
                v.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

            }
        }).setLayoutRes(R.layout.select_change_image)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        //选择图片
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                if (data.getData() != null) {
                    //TODO

                    String path = FileUtils.getFilePath(this, data.getData());//图片路径
//                    String path = "storage/emulated/0/Pictures/Screenshots/"+System.currentTimeMillis()+".jpg";//图片路径
                    Bitmap bm = null;
                    ///storage/emulated/0/Pictures/Screenshots/Screenshot_20190123-214734.jpg
                    File file = new File(path);
                    if (file.exists()) {
                        bm = BitmapFactory.decodeFile(FileUtils.getFilePath(this, data.getData()));
                        bm = BitmapCompressUtils.imageZoom(bm, 50);
                        file = ImRezUtils.saveBitmapFile(bm, path);
                        circleImageView.setImageBitmap(bm);
                    }
                    //上传图片
                    if (FileUtils.getFilePath(this, data.getData()) != null) {
                        // TODO 上传服务器
                        uploadImg(file);
                    } else {
                        NewsToastUtils.showToast(PartMineInfoActivity.this, "文件不存在！");
                    }
                } else {
                    Log.e("TAG", "onActivityResult: 为空");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //拍照
        if (requestCode == PICK_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                String path = Constant.DIR_INFO.APP_DIR + "/head.jpg";
                File temp = new File(path);
                if (temp.exists()) {
                    // TODO 上传服务器
                    Bitmap bm = BitmapFactory.decodeFile(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                    bm = BitmapCompressUtils.imageZoom(bm, 50);
                    temp = ImRezUtils.saveBitmapFile(bm, path);
                    circleImageView.setImageBitmap(bm);
                    uploadImg(temp);
                } else {
                    NewsToastUtils.showToast(PartMineInfoActivity.this, "文件不存在！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //修改昵称
        if (requestCode == CHANGMYNAME && resultCode == RESULT_OK) {
            assert data != null;
            nickname = data.getStringExtra("name");
            tv_name.setText(nickname);
        }
    }

    //上传图像
    private void uploadImg(File file) {
        try {
            Dialog dialog = new CenterDialog(R.layout.loading_layout, PartMineInfoActivity.this).showLoad("正在上传图片...");
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            String userId = SPUtils.get(App.getContext(), "userId", "") + "";
            Task.getApiService().upLoadImg(userId, body).enqueue(new MyCallback<PartBaseEntity>(PartMineInfoActivity.this) {
                @Override
                protected void onSuccess(Response<PartBaseEntity> response) {
                    dialog.dismiss();
                    assert response.body() != null;
                    NewsToastUtils.showToast(PartMineInfoActivity.this, response.body().getMsg());
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    serverUrl = jsonObject.getString("serverUrl");
                    SPUtils.put(App.getContext(),"serverUrl",serverUrl);
                }

                @Override
                protected void onFailure(Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void setListen() {

    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_part_mine_info;
    }

    @OnClick({R.id.iv_confirm, R.id.rel_name, R.id.rel_head})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_confirm: //保存修改内容
                Intent it = new Intent();
                it.putExtra("name", tv_name.getText().toString());
                it.putExtra("head", serverUrl);
                setResult(RESULT_OK, it);
                SPUtils.put(App.getContext(),"nickName",tv_name.getText().toString());
                finish();
                break;
            case R.id.rel_name://修改名字
                startActivityForResult(new Intent(this, PartEditorActivity.class)
                        .putExtra("title", "真实姓名"), CHANGMYNAME);
                break;
            case R.id.rel_head://修改头像
                getPermission();
                break;
        }
    }


    @Override
    public void initView() {
        new TitleBuilder(this).setTitleText("个人信息")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public void initData() {
        Intent it = getIntent();//, R.drawable.home_banner_pic
        String head = it.getStringExtra("head")+"";
        if (head.equals("")){
            Picasso.with(this).load(R.mipmap.head).into(circleImageView);
        }else {
            Picasso.with(this).load(head).into(circleImageView);
        }

        String name = it.getStringExtra("name");
        tv_name.setText(name);


    }
}
